package com.dzk.cp.c11x5.util;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.struts2.ServletActionContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.dzk.cp.c11x5.constant.R5Type;
import com.dzk.cp.c11x5.pojo.GdR5;
import com.dzk.cp.c11x5.pojo.JxR5;
import com.dzk.cp.c11x5.pojo.R5;
import com.dzk.cp.c11x5.pojo.SdR5;
import com.dzk.cp.c11x5.service.R5Service;

@SuppressWarnings("unchecked")
public class SpringBeanUtils {
	
	private static Map<R5Type, R5Service<? extends R5>> r5ServiceTypeMap;
	
	private static Map<Class<? extends R5>, R5Service<? extends R5>> r5ServiceClassMap;
	
	private static WebApplicationContext ctx;
	
	static {
		getWebContext();
		
		r5ServiceTypeMap = new HashMap<R5Type, R5Service<? extends R5>>();
		r5ServiceTypeMap.put(R5Type.SD, (R5Service<SdR5>) ctx.getBean("sdR5Service"));
		r5ServiceTypeMap.put(R5Type.JX, (R5Service<JxR5>) ctx.getBean("jxR5Service"));
		r5ServiceTypeMap.put(R5Type.GD, (R5Service<GdR5>) ctx.getBean("gdR5Service"));
		
		r5ServiceClassMap = new HashMap<Class<? extends R5>, R5Service<? extends R5>>();
		r5ServiceClassMap.put(SdR5.class, (R5Service<SdR5>) ctx.getBean("sdR5Service"));
		r5ServiceClassMap.put(JxR5.class, (R5Service<JxR5>) ctx.getBean("jxR5Service"));
		r5ServiceClassMap.put(GdR5.class, (R5Service<GdR5>) ctx.getBean("gdR5Service"));
	}
	
	public static WebApplicationContext getWebContext() {
		if (ctx == null) {
			ServletContext servletContext = ServletActionContext.getServletContext();
			ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		}
		return ctx;
	}

	public static R5Service<? extends R5> getR5Service(Integer code) {
		R5Service<? extends R5> r5Service = r5ServiceTypeMap.get(R5Type.get(code));
		if (r5Service == null) {
			r5Service = r5ServiceTypeMap.get(R5Type.SD);
		}
		return r5Service;
	}
	
	public static R5Service<? extends R5> getR5Service(Class<? extends R5> r5Class) {
		R5Service<? extends R5> r5Service = r5ServiceTypeMap.get(r5Class);
		if (r5Service == null) {
			r5Service = r5ServiceTypeMap.get(SdR5.class);
		}
		return r5Service;
	}

}
